package edu.ou.herbarium.main;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.ServerSocket;
import java.util.ArrayList;
import java.util.List;
import javax.imageio.ImageIO;

import org.eclipse.nebula.widgets.gallery.DefaultGalleryGroupRenderer;
import org.eclipse.nebula.widgets.gallery.DefaultGalleryItemRenderer;
import org.eclipse.nebula.widgets.gallery.Gallery;
import org.eclipse.nebula.widgets.gallery.GalleryItem;
import org.eclipse.nebula.widgets.tablecombo.TableCombo;
import org.eclipse.swt.*;
import org.eclipse.swt.browser.Browser;
import org.eclipse.swt.custom.*;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.MenuEvent;
import org.eclipse.swt.events.MenuListener;
import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.ImageData;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.graphics.Rectangle;
import org.eclipse.swt.layout.*;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.forms.widgets.Form;
import org.eclipse.ui.forms.widgets.FormToolkit;
import org.eclipse.ui.forms.widgets.Section;


import edu.ou.herbarium.image.ImageUtils;
import edu.ou.herbarium.sharedata.*;
import edu.ou.herbarium.threads.DataLoader;
import edu.ou.herbarium.threads.ShareData;
import edu.ou.herbarium.threads.ShareData2;
import edu.ou.herbarium.threads.TransferData;
import edu.ou.herbarium.threads2.*;
import edu.ou.herbarium.wsclient.Collector;
import edu.ou.herbarium.wsclient.DataUtilsDelegate;
import edu.ou.herbarium.wsclient.DataUtilsService;
import edu.ou.herbarium.wsclient.Specimen;

public class Main {

	static int srcWidth = 2848;//8082
	static int srcHeight = 4288;
	static int divideFactor = 2;
	static boolean createdScreenBar = false;
	static String localDir = "";
	public static int userId = 0;
//	
//	public static Color error = new Color(Display.getCurrent(),239,160,147);
//	public static Color warning = new Color(Display.getCurrent(),252,232,179);
	
	static String SERVER_ADDR = "http://127.0.0.1:8082/HerbService/";
//	static String SERVER_ADDR = "http://127.0.0.1:8081/HerbService/";
	public static final String MAIN_DIR = "C:/Users/eming/Desktop/image/"; 
	
	private static SelectionListener tableSelectionListener = null;
	private static SelectionListener buttonSelectionListener = null;
	private static Listener tableListener = null;
	
	
	static void createMenuBar(Shell s) {
		Menu bar = Display.getCurrent().getMenuBar();
		boolean hasAppMenuBar = (bar != null);
		if (bar == null) {
			bar = new Menu(s, SWT.BAR);
		}

		if (!createdScreenBar || !hasAppMenuBar) {
			MenuItem item = new MenuItem(bar, SWT.CASCADE);
			item.setText("Action");
			Menu menu = new Menu(item);
			item.setMenu(menu);
			menu.addMenuListener(new MenuListener() {

				public void menuHidden(MenuEvent e) {
					System.out.println("Menu closed: " + e);
				}

				public void menuShown(MenuEvent e) {
					System.out.println("Menu open: " + e);
				}
			});
			MenuItem newWindow = new MenuItem(menu, SWT.PUSH);
			newWindow.setText("Start");
			newWindow.setAccelerator(SWT.MOD1 | 'N');
			newWindow.addListener(SWT.Selection, new Listener() {

				@Override
				public void handleEvent(Event arg0) {
					// TODO Auto-generated method stub
					
				}
				
			});
			if (!hasAppMenuBar)
				s.setMenuBar(bar);
			createdScreenBar = true;
		}
	}

	public static Shell createInputShell() {
		Display display = Display.getCurrent();
		Shell shell = new Shell();

		return shell;
	}
	
	public static void updateGallery(List<Specimen> specimens, Gallery gallery,String type){
		gallery.removeAll();
		for(Specimen spec : specimens){
			if(type.equals("missing")){
				if(spec.getMissingInfo()==null||spec.getMissingInfo()!=1){
					continue;
				}
			}
			else if(type.equals("error")){
				if(spec.getImageError()==null||spec.getImageError()!=1){
					continue;
				}
			}
			boolean added = false;
			String qrcode = spec.getWatermark();//fake
			for(GalleryItem item : gallery.getItems()){
				String itemQR = item.getText();
				if(itemQR.equals(qrcode)){
					item.setExpanded(true);
					GalleryItem imageItem = new GalleryItem(item,0, SWT.NONE);
					if(spec.getHandler().length!=0)
					imageItem.setImage( new Image(Display.getCurrent(),
							new ByteArrayInputStream(spec.getHandler())));
					imageItem.setText( spec.getBarcode());
					if(spec.getMissingInfo()!=null&&spec.getMissingInfo()==1){
						
						imageItem.setBackground(new Color(Display.getCurrent(),255,255,200));
					}
					if(spec.getImageError()!=null&&spec.getImageError()==1){
						imageItem.setBackground(new Color(Display.getCurrent(),255,200,200));
					}
					imageItem.setData(spec);
					imageItem.setData("path",spec.getCollectionCode());
					GalleryItem [] items = new GalleryItem [] {imageItem};
					gallery.setSelection(items);
					added = true;
					break;
				}
			}
			if(added==false){
				GalleryItem item = new GalleryItem(gallery, SWT.NONE);
				item.setText(qrcode);
				item.setExpanded(true);
				GalleryItem imageItem = new GalleryItem(item,0, SWT.NONE);
				imageItem.setImage( new Image(Display.getCurrent(),
						new ByteArrayInputStream(spec.getHandler())));
				imageItem.setText( spec.getBarcode());
				imageItem.setData(spec);
				if(spec.getMissingInfo()!=null&&spec.getMissingInfo()==1){
					imageItem.setBackground(new Color(Display.getCurrent(),255,255,200));
				}
				if(spec.getImageError()!=null&&spec.getImageError()==1){
					imageItem.setBackground(new Color(Display.getCurrent(),255,200,200));
				}
				imageItem.setData("path",spec.getCollectionCode());
				GalleryItem [] items = new GalleryItem [] {imageItem};
				gallery.setSelection(items);
			}
		}
	}
	

	public static Shell createShell() {
		
		final Display display = Display.getCurrent();
		final Shell shell = new Shell();
		final ShareData1 d1 = new ShareData1();
		final ShareData5 d5 = new ShareData5();
		final ShareData6 d6 = new ShareData6();
		final ShareData7 d7 = new ShareData7();
		final ShareData8 d8 = new ShareData8();
		final ShareData9 d9 = new ShareData9();
		final ShareData10 d10 = new ShareData10();
		final ErrorData de = new ErrorData();
		createMenuBar(shell);
		
			
		DataThread tdata = new DataThread(d1,d5,de);
		ServerThread server = new ServerThread(d1,de);
		ImageThread image = new ImageThread(d5,d6,de);
		FileThread file = new FileThread(de,d6,d7,d9);
		RemoteThread remote = new RemoteThread(d7,d8);
		ConveyorThread conveyor = new ConveyorThread(de);
		
		tdata.start();
		server.start();
		image.start();
		file.start();
		remote.start();
		conveyor.start();
			
		
		
		shell.setLayout(new FillLayout());
		
		

		final SashForm form = new SashForm(shell, SWT.HORIZONTAL);
		form.setLayout(new FillLayout());
		Composite child1 = new Composite(form, SWT.NONE);
		child1.setLayout(new GridLayout());
		final GridData data = new GridData();
		data.grabExcessHorizontalSpace = true;
		data.grabExcessVerticalSpace = true;
		data.minimumHeight = 700;
		data.minimumWidth = 210;
		child1.setLayoutData(data);
		final GridData data2 = new GridData();
		data2.grabExcessHorizontalSpace = true;
		data2.grabExcessVerticalSpace = true;
		data2.minimumHeight = 25;
		data2.minimumWidth = 210;
		
		final Combo combo = new Combo(child1,SWT.NONE);
		combo.setLayoutData(data2);
		combo.add("all");
		combo.add("missing information");
		combo.add("image error");
		
		
		/**
		Group group = new Group (child1, SWT.NONE);
		final GridData data2 = new GridData();
		data2.grabExcessHorizontalSpace = true;
		data2.grabExcessVerticalSpace = true;
		data2.minimumHeight = 40;
		data2.minimumWidth = 195;
		data2.horizontalAlignment = 1;
		data2.verticalAlignment = 1;
		GridLayout layout = new GridLayout ();
		layout.numColumns = 10;
		layout.marginTop = 1;
		layout.marginHeight = 1;
		layout.marginLeft = 1;
		layout.marginWidth = 1;
		group.setLayout (layout);
		group.setLayoutData(data2);
		
		Button b = new Button(group, SWT.NONE);
		b.setText("|<");
		b.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));
		Button b2 = new Button(group, SWT.NONE);
		b2.setText("<");
		b2.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));
		
		Label label = new Label(group, SWT.NONE);
		label.setText("Page:");
		
//		Text text = new Text(group, SWT.BORDER);
//		text.setText("0");
//		text.setSize(40, 40);
		Combo combo = new Combo(group,SWT.BORDER);
		combo.setItems(new String [] {"0"});
		
		Button b3 = new Button(group, SWT.NONE);
		b3.setText(">");
		b3.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));
		Button b4 = new Button(group, SWT.NONE);
		b4.setText(">|");
		b4.setLayoutData(new GridData(SWT.LEFT, SWT.TOP, true, true, 1, 1));
		
		Text text2 = new Text(group, SWT.BORDER);
		text2.setText("0");
		text2.setSize(40, 40);
		*/
		/**
		final TableCombo combo = new TableCombo(child1,SWT.NONE);
		combo.setEditable(false);
		TableColumn tc0 = new TableColumn(combo.getTable(),SWT.NONE);
		TableColumn tc1 = new TableColumn(combo.getTable(),SWT.NONE);
		TableItem empty = new TableItem(combo.getTable(),SWT.NONE);
		TableItem warning = new TableItem(combo.getTable(),SWT.NONE);
		
		warning.setBackground(1,new Color(Display.getCurrent(),255,255,200));
		warning.setImage(0,new Image(Display.getCurrent(),localDir+"img/alert_obj.gif"));
		warning.setText(1,"missing information");
		
		TableItem error = new TableItem(combo.getTable(),SWT.NONE);
		error.setBackground(1,new Color(Display.getCurrent(),255,200,200));
		error.setImage(0,new Image(Display.getCurrent(),localDir+"img/error_tsk.gif"));
		error.setText(1,"Image Error");
		combo.setLayoutData(data2);
		combo.addSelectionListener(new SelectionListener(){

			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub
				System.out.println(arg0);
			}

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub
				System.out.println(arg0);
			}
			
		});
		*/
		
//		error.addSelectionListener();
		
//		final Table table1 = new Table(child1, SWT.H_SCROLL | SWT.V_SCROLL |SWT.FULL_SELECTION);
		final Gallery gallery = new Gallery(child1, SWT.V_SCROLL | SWT.VIRTUAL);
		gallery.setSize(210, 550);
		DefaultGalleryGroupRenderer gr = new DefaultGalleryGroupRenderer();
		gr.setItemSize(190, 225);
		gr.setAutoMargin(true);
		
		gr.setMinMargin(1);
		DefaultGalleryItemRenderer ir = new DefaultGalleryItemRenderer();
		ir.setDropShadows(true);
		ir.setDropShadowsSize(10);
		

		gallery.setGroupRenderer(gr);
		gallery.setItemRenderer(ir);
		gallery.setVirtualGroups(true);
		gallery.setLayoutData(data);
		
		DataUtilsService service = new DataUtilsService();
		DataUtilsDelegate delegate = service.getDataUtilsPort();
		final List<Specimen> specimens = delegate.getSpecimens();
		updateGallery(specimens, gallery, "");
combo.addSelectionListener(new SelectionListener(){
			
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void widgetSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub
				if(combo.getSelectionIndex()==1){
					updateGallery(specimens,gallery,"missing");
				}
				else if(combo.getSelectionIndex()==2){
					updateGallery(specimens,gallery,"error");
				}
			}
			
			public void updateGallery(List<Specimen> specimens, Gallery gallery,String type){
				gallery.removeAll();
				for(Specimen spec : specimens){
					if(type.equals("missing")){
						if(spec.getMissingInfo()==null||spec.getMissingInfo()!=1){
							continue;
						}
					}
					else if(type.equals("error")){
						if(spec.getImageError()==null||spec.getImageError()!=1){
							continue;
						}
					}
					boolean added = false;
					String qrcode = spec.getWatermark();//fake
					for(GalleryItem item : gallery.getItems()){
						String itemQR = item.getText();
						if(itemQR.equals(qrcode)){
							item.setExpanded(true);
							GalleryItem imageItem = new GalleryItem(item,0, SWT.NONE);
							if(spec.getHandler().length!=0)
								imageItem.setImage( new Image(Display.getCurrent(),
									new ByteArrayInputStream(spec.getHandler())));
							imageItem.setText( spec.getBarcode());
							if(spec.getMissingInfo()!=null&&spec.getMissingInfo()==1){
								
								imageItem.setBackground(new Color(Display.getCurrent(),255,255,200));
							}
							if(spec.getImageError()!=null&&spec.getImageError()==1){
								imageItem.setBackground(new Color(Display.getCurrent(),255,200,200));
							}
							imageItem.setData(spec);
							imageItem.setData("path",spec.getCollectionCode());
							GalleryItem [] items = new GalleryItem [] {imageItem};
							gallery.setSelection(items);
							added = true;
							break;
						}
					}
					if(added==false){
						GalleryItem item = new GalleryItem(gallery, SWT.NONE);
						item.setText(qrcode);
						item.setExpanded(true);
						GalleryItem imageItem = new GalleryItem(item,0, SWT.NONE);
						if(spec.getHandler().length!=0)
							imageItem.setImage( new Image(Display.getCurrent(),
								new ByteArrayInputStream(spec.getHandler())));
						imageItem.setText( spec.getBarcode());
						imageItem.setData(spec);
						if(spec.getMissingInfo()!=null&&spec.getMissingInfo()==1){
							imageItem.setBackground(new Color(Display.getCurrent(),255,255,200));
						}
						if(spec.getImageError()!=null&&spec.getImageError()==1){
							imageItem.setBackground(new Color(Display.getCurrent(),255,200,200));
						}
						imageItem.setData("path",spec.getCollectionCode());
						GalleryItem [] items = new GalleryItem [] {imageItem};
						gallery.setSelection(items);
					}
				}
			}
		});
//		gallery.addListener(SWT.SetData, new Listener() {
//
//			public void handleEvent(Event event) {
//				GalleryItem item = (GalleryItem) event.item;
//				int index;
//				if (item.getParentItem() != null) {
//					index = item.getParentItem().indexOf(item);
//					item.setItemCount(0);
//					item.setText("BARCODE #" + index); //$NON-NLS-1$
//				} else {
//					index = gallery.indexOf(item);
//					item.setItemCount(specimens.size());
//					item.setText("QR Code #" + index); //$NON-NLS-1$
//				}
//
//				// Your image here
//				if(index<specimens.size()){
//					item.setImage(new Image(Display.getCurrent(), new ByteArrayInputStream(specimens.get(index).getHandler())));
//					item.setData(specimens.get(index));
//				}
//			}
//		});
//		gallery.setItemCount(3);
		
		//******************************************************************************/
		// start monitoring threads 
		//******************************************************************************/
		Thread monitorPicture = new Thread() {
			//Acquire insert specimen
			public void run () {
				while(true){
					if (gallery.isDisposed())
						return;
//					final TransferData td = sdata.getShareChar();
					final TransferData8 data8 = d8.getShareData();
					display.asyncExec(new Runnable() {
						public void run() {
							boolean added = false;
							Specimen spec = data8.getSpec();
							String qrcode = data8.getQrCode();
							for(GalleryItem item : gallery.getItems()){
								String itemQR = item.getText();
								if(itemQR.equals(qrcode)){
									item.setExpanded(true);
									GalleryItem imageItem = new GalleryItem(item,0, SWT.NONE);
									imageItem.setImage( new Image(Display.getCurrent(),
											new ByteArrayInputStream(data8.getByte4())));
									imageItem.setText( spec.getBarcode());
									imageItem.setData(spec);
									if(spec.getMissingInfo()!=null&&spec.getMissingInfo()==1){
										
										imageItem.setBackground(new Color(Display.getCurrent(),255,200,200));
									}
									if(spec.getImageError()!=null&&spec.getImageError()==1){
										imageItem.setBackground(new Color(Display.getCurrent(),255,255,200));
									}
									imageItem.setData("path",spec.getCollectionCode());
									GalleryItem [] items = new GalleryItem [] {imageItem};
									gallery.setSelection(items);
									added = true;
									break;
								}
							}
							if(added==false){
								
								GalleryItem item = new GalleryItem(gallery, SWT.NONE);
								item.setText(qrcode);
								item.setExpanded(true);
								GalleryItem imageItem = new GalleryItem(item, 0,SWT.NONE);
								imageItem.setImage( new Image(Display.getCurrent(),
										new ByteArrayInputStream(data8.getByte4())));
								imageItem.setText( spec.getBarcode());
								imageItem.setData(spec);
								if(spec.getMissingInfo()!=null&&spec.getMissingInfo()==1){
									
									imageItem.setBackground(new Color(Display.getCurrent(),255,200,200));
								}
								if(spec.getImageError()!=null&&spec.getImageError()==1){
									imageItem.setBackground(new Color(Display.getCurrent(),255,255,200));
								}
								imageItem.setData("path",spec.getCollectionCode());
								GalleryItem [] items = new GalleryItem [] {imageItem};
								gallery.setSelection(items);
								
							}
						}
					});
				}
			}
		};
		monitorPicture.start();
		
		
		//******************************************************************************/
		// start monitoring threads 
		//******************************************************************************/
//		Thread thread = new Thread () {
//			public void run () {
//				while(true){
//				if (table1.isDisposed())
//					return;
//				final TransferData td = sdata.getShareChar();
//				display.asyncExec(new Runnable() {
//					public void run() {
//							TableItem ti = new TableItem(table1,SWT.FULL_SELECTION,0);
//							Image img = new Image(Display.getCurrent(),
//									new ByteArrayInputStream(td.getBytes2()));
//							ti.setImage(1, img);
//							ti.setData(td.getSpec());
//							ti.setData("path", td.getName());
//							table1.setSelection(ti);
//						}
//					});
//				}
//			}
//		};
//		thread.start();
		

		final Composite child2 = new Composite(form, SWT.NONE);
		child2.setLayout(new FillLayout());
		
		final GridData gdata = new GridData();
		gdata.horizontalAlignment = GridData.FILL;
		gdata.verticalAlignment = GridData.FILL;
		gdata.horizontalSpan = 3;
		gdata.grabExcessHorizontalSpace = true;
		gdata.grabExcessVerticalSpace = true;
		final ArrayList<Browser> bs = new ArrayList<Browser>();
		
		final Composite child3 = new Composite(form, SWT.NONE);
		form.setWeights(new int[] { 16, 52, 32});
		GridLayout gridLayout = new GridLayout();
		child3.setLayout(gridLayout);
		
		
		final Label label0 = new Label(child3,SWT.NONE);
//		label0.setText("Specimen:  "+spec.getBarcode());
		label0.setText("Specimen:  ");
		label0.setFont( new Font(display,"Arial", 14, SWT.BOLD ) );
		final Table table = new Table(child3,SWT.FULL_SELECTION);
		table.setData("name", "table");
		final Button submitButton = new Button(child3, SWT.NONE);
		submitButton.setData("name","submitButton");
		final Label label2 = new Label(child3,SWT.NONE);
		label2.setData("name", "label2");
		label2.setText("Modification Save Successfully");
		label2.setFont( new Font(display,"Arial", 10, SWT.BOLD ) );
		label2.setForeground(new Color(Display.getCurrent(),0,128,64));
		label2.setVisible(false);
		
		final Label label3 = new Label(child3,SWT.NONE);
		label3.setText("Modification Save Failed");
		label3.setFont( new Font(display,"Arial", 10, SWT.BOLD ) );
		label3.setForeground(new Color(Display.getCurrent(),128,0,0));
		label3.setVisible(false);
		label3.setData("name", "label3");
		
		final GridData data3 = new GridData();
		data3.grabExcessHorizontalSpace = true;
		data3.grabExcessVerticalSpace = true;
		data3.minimumHeight = 300;
		data3.minimumWidth = 405;
		
		final Group infog = new Group(child3,SWT.NONE);
		infog.setText("info");
		infog.setLayout (new FillLayout ());
		infog.setLayoutData(data3);
		final Table table2 = new Table(infog,SWT.BOTTOM|SWT.FULL_SELECTION);
		table2.setLinesVisible(false);
		table2.setData("name", "table2");
		table2.setBackground(new Color(Display.getCurrent(),240,240,240));
//		table2.setLayoutData(data3);
		table.setLayoutData(data3);
		TableColumn column21 = new TableColumn(table2,SWT.NONE);
		column21.setWidth(50);
		TableColumn column22 = new TableColumn(table2,SWT.NONE);
		column22.setWidth(375);
		
		TableItem item = new TableItem(table2,SWT.None);
		item.setImage(0,new Image(Display.getCurrent(),localDir+"img/rotate_0.gif"));
//		Thread monitorIDrop = new Thread() {
//			//Acquire insert specimen
//			public void run () {
//				while(true){
//					if (table2.isDisposed())
//						return;
//					final String info = de.getShareData();
//				}
//			}
//		};
//		monitorIDrop.start();
		
		Thread monitorError = new Thread() {
			
			ArrayList<Integer> list = new ArrayList<Integer>();
			int id = 0;
			//Acquire insert specimen
			public void run () {
				while(true){
					if (table2.isDisposed())
						return;
					final String info = de.getShareData();
					final String type = info.split("::")[0].split("_")[0];
					final String name = info.split("::")[0].split("_")[1];
					final int number = Integer.parseInt(info.split("::")[0].split("_")[2]);
					if(number>1000){
						for(int i=0;i<list.size();i++){
							if(list.get(i)==number-1000){
								RemoveRunnable rr = new RemoveRunnable(i+1,table2);
								display.asyncExec(rr);
								list.remove(i);
							}
						}
					}
					else{
						boolean flag = false;
						for(Integer num : list){
							if(num==number){
								flag = true;
								break;
							}
						}
						if(flag==false){
							if(type.equals("INFO")){
								if(name.equals("CLIENT")){
									display.asyncExec(new Runnable() {
										public void run() {
											TableItem ti = new TableItem(table2,SWT.FULL_SELECTION,1);
											ti.setImage(0,new Image(Display.getCurrent(),localDir+"img/information.gif"));
											ti.setText(1, "Client Connected:"+info.split("::")[1]);
											list.add(0, number);
										}
									});
								}
								else if(name.equals("CONVEYOR")){
									display.asyncExec(new Runnable() {
										public void run() {
											TableItem ti = table2.getItem(0);
											ti.setImage(0,new Image(Display.getCurrent(),localDir+"img/rotate_"+id+".gif"));
											id++;
											if(id>19) id=0;
										}
									});
								}
							}
							else if(type.equals("ERROR")){
								if(name.equals("CAMERA")){
									display.asyncExec(new Runnable() {
										public void run() {
											TableItem ti = new TableItem(table2,SWT.FULL_SELECTION,1);
											ti.setImage(0,new Image(Display.getCurrent(),localDir+"img/alert_obj.gif"));
											ti.setText(1, "Camera Error:"+info.split("::")[1]);
											list.add(0, number);
										}
									});
								}
								else if(name.equals("COLOR")){
									display.asyncExec(new Runnable() {
										public void run() {
											TableItem ti = new TableItem(table2,SWT.FULL_SELECTION,1);
											ti.setImage(0,new Image(Display.getCurrent(),localDir+"img/alert_obj.gif"));
											ti.setText(1, "Color Error:"+info.split("::")[1]);
											list.add(0, number);
										}
									});
								}
							}
						}
					}
				}
			}
		};
		monitorError.start();
		submitButton.setEnabled(false);
		
		submitButton.setText("Submit Modification");
		TableColumn column = new TableColumn(table,SWT.NONE);
		column.setWidth(200);
		TableColumn column2 = new TableColumn(table,SWT.NONE);
		column2.setWidth(200);
		
		final TableItem itemName = new TableItem(table,SWT.NONE);
		itemName.setText(0,"Scientific Name:");
		final TableItem itemFamily = new TableItem(table, SWT.NONE);
		itemFamily.setText(0, "Family:");
		itemFamily.setData("setFamily");
		final TableItem itemGenus = new TableItem(table, SWT.NONE);
		itemGenus.setText(0, "Genus:");
		itemGenus.setData("setGenus");
		final TableItem itemSpecies = new TableItem(table, SWT.NONE);
		itemSpecies.setText(0, "Species:");
		itemSpecies.setData("setSpecies");
		final TableItem itemCollectAt = new TableItem(table, SWT.NONE);
		itemCollectAt.setText(0, "Collect At:");
		itemCollectAt.setData("setCountry");
		final TableItem itemCollectAtDarwin = new TableItem(table, SWT.NONE);
		itemCollectAtDarwin.setText(0, "Name in Darwin's time:");
		itemCollectAtDarwin.setData("setDcountry");
		final TableItem itemSheetNote = new TableItem(table, SWT.NONE);
		itemSheetNote.setText(0, "Sheet Notes:");
		itemSheetNote.setData("setSheetNotes");
		final TableItem itemState = new TableItem(table, SWT.NONE);
		itemState.setText(0, "State:");
		itemState.setData("setStateProvince");
		final TableItem itemTown = new TableItem(table, SWT.NONE);
		itemTown.setText(0, "Town:");
		itemTown.setData("setTown");
		final TableItem blank = new TableItem(table, SWT.NONE);
		blank.setText(0, "Collectors:");
		
		gallery.addSelectionListener(new SelectionListener() {
			boolean flag = false;
			@Override
			public void widgetDefaultSelected(SelectionEvent arg0) {
				// TODO Auto-generated method stub

			}

			@Override
			public void widgetSelected(SelectionEvent arg0) {
//				boolean flag = false;
//				for(TableItem item : table.getItems()){
//					if(((String)item.getData("modified")).equals("true")){
//						flag = true;
//						break;
//					}
//				}
//				if(flag){
//					///
//				}
				if(arg0.item.getData()!=null){
					if(tableSelectionListener!=null){
						table.removeSelectionListener(tableSelectionListener);
						tableSelectionListener = null;
					}
					
					if(tableListener!=null){
						table.removeListener(SWT.MouseDoubleClick, tableListener);
						tableListener = null;
					}
					
					if(buttonSelectionListener!=null){
						submitButton.removeSelectionListener(buttonSelectionListener);
						tableSelectionListener = null;
					}
					
					for(Object o : child3.getChildren()){
						if(o.getClass().getName().equals("org.eclipse.swt.widgets.Button")){
							Button b = (Button)o;
							if(b.isEnabled()){
								int style = SWT.APPLICATION_MODAL | SWT.YES | SWT.NO;
							    MessageBox messageBox = new MessageBox(shell, style);
							    messageBox.setText("You have unsaved modification");
							    messageBox.setMessage("Save modification?");
							    messageBox.open();
							}
						}
					}
					final Specimen spec = (Specimen)arg0.item.getData();
					String link = (String)arg0.item.getData("path");
					
					for(Control ctrl : child3.getChildren()){
						String name = (String)ctrl.getData("name");
						if(name!=null){
							if(name.equals("label2")){
								Label l2 = (Label)ctrl;
								l2.setVisible(false);
							}
							if(name.equals("label3")){
								Label l3 = (Label)ctrl;
								l3.setVisible(false);
							}
							if(name.equals("submitButton")){
								Button b = (Button)ctrl;
								b.setEnabled(false);
							}
							if(name.equals("table")){
								Table t = (Table)ctrl;
								for(TableItem ti : t.getItems()){
									ti.setBackground(new Color(Display.getCurrent(),255,255,255));
									ti.setText(1,"");
								}
							}
						}
					}
					
					
					
					itemName.setText(1,spec.getScientificName());
					itemFamily.setText(1, spec.getFamily());
					itemGenus.setText(1, spec.getGenus());
					itemSpecies.setText(1, spec.getSpecificEpithet());
					itemCollectAt.setText(1, spec.getCountry());
					itemCollectAtDarwin.setText(1, spec.getDarwinCountry());
					itemSheetNote.setText(1, spec.getSheetNotes());
					itemState.setText(1, spec.getStateProvince());
					itemTown.setText(1, spec.getTown());
					
					final TableEditor editor = new TableEditor(table);
					//The editor must have the same size as the cell and must
					//not be any smaller than 50 pixels.
					editor.horizontalAlignment = SWT.LEFT;
					editor.grabHorizontal = true;
					editor.minimumWidth = 50;
					// editing the second column
					final int EDITABLECOLUMN = 1;
					tableSelectionListener = new SelectionListener(){
						@Override
						public void widgetDefaultSelected(SelectionEvent arg0) {
							// TODO Auto-generated method stub
							
						}
						@Override
						public void widgetSelected(SelectionEvent arg0) {
							// TODO Auto-generated method stub
							Control oldEditor = editor.getEditor();
							if (oldEditor != null) oldEditor.dispose();
						}
					};
					table.addSelectionListener(tableSelectionListener);
					
					
					tableListener = new Listener() {
						@Override
						public void handleEvent(Event arg0) {
							// TODO Auto-generated method stub
							Point pt = new Point(arg0.x,arg0.y);
							for(final TableItem item : table.getItems()){
								for (int i=0; i<table.getColumnCount (); i++) {
									Rectangle rect = item.getBounds (i);
									if(rect.contains(pt)){
										Control oldEditor = editor.getEditor();
										if (oldEditor != null) oldEditor.dispose();
										Text newEditor = new Text(table, SWT.NONE);
										newEditor.setText(item.getText(EDITABLECOLUMN));
										newEditor.addDisposeListener(new DisposeListener(){
											@Override
											public void widgetDisposed(
													DisposeEvent arg0) {
												// TODO Auto-generated method stub
												Text text = (Text)editor.getEditor();
												editor.getItem().setText(EDITABLECOLUMN, text.getText());
												String methodName = (String)item.getData();
												for(Method m : spec.getClass().getMethods()){
													if(m.getName().equals(methodName)){
														try {
															m.invoke(spec, new Object[] {  text.getText() });
														} catch (IllegalArgumentException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														} catch (IllegalAccessException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														} catch (InvocationTargetException e) {
															// TODO Auto-generated catch block
															e.printStackTrace();
														}
														break;
													}
												}
												
												item.setBackground(new Color(Display.getCurrent(),255,250,160));
												item.setData("modified","true");
												submitButton.setEnabled(true);
											}
										});
										
										newEditor.selectAll();
										newEditor.setFocus();
										editor.setEditor(newEditor, item, EDITABLECOLUMN);
										break;
									}
								}
							}
						}
					};
					
					table.addListener(SWT.MouseDoubleClick, tableListener);
					
					buttonSelectionListener = new SelectionListener(){
						@Override
						public void widgetDefaultSelected(SelectionEvent arg0) {
							// TODO Auto-generated method stub
							
						}
						@Override
						public void widgetSelected(SelectionEvent arg0) {
							System.out.println("selectedddd");
							// TODO Auto-generated method stub
							DataUtilsService service = new DataUtilsService();
							DataUtilsDelegate delegate = service.getDataUtilsPort();
							delegate.updateSpecimen(spec);
							for(TableItem item : table.getItems()){
								item.setBackground(new Color(Display.getCurrent(),255,255,255));
								submitButton.setEnabled(false);
							}
							label2.setVisible(true);
						}
					};
					
					submitButton.addSelectionListener(buttonSelectionListener);
					// TODO Auto-generated method stub
					try {
						if(bs.size()!=0){
							bs.get(0).dispose();
							bs.remove(0);
						}
						Browser browser = new Browser(child2, SWT.NONE);
						browser.setUrl(SERVER_ADDR+"test.html?file="+link);
						browser.setLayoutData(gdata);
						bs.add(browser);
						if(!flag){
							shell.setSize(shell.getSize().x, shell.getSize().y+1);
							flag = true;
						}
						else{
							shell.setSize(shell.getSize().x, shell.getSize().y+1);
							flag = false;
						}
					} catch (SWTError e) {
						System.out.println("Could not instantiate Browser: " + e.getMessage());
						display.dispose();
						return;
					}
				}
			}
		});
		return shell;
	}

	public static void main(String[] args) {
		localDir = System.getProperty("user.dir").replaceAll("\\\\", "/")+"/";
		final Display display = new Display();
		LoginDialog dialog = new LoginDialog(display.getActiveShell());
		dialog.open();
		if(userId==0){
			return;
		}
		Shell shell = createShell();
//		shell.setMaximized(true);
		shell.setSize(1360, 700);
		shell.setLocation(0, 0);
		shell.open();
		while (!shell.isDisposed()) {
			if (!display.readAndDispatch())
				display.sleep();
		}
		display.dispose();
	}
}

class ItemSelected extends SelectionAdapter {
	
	private TableCombo tc;
	private String text;
	
	public ItemSelected(TableCombo tc, String text) {
		this.tc = tc;
		this.text = text;
	}

	public void widgetSelected(SelectionEvent e) {
		tc.setText(text);
		System.out.println(e);
	}
}

class RemoveRunnable implements Runnable{
	
	int index;
	Table table;
	public RemoveRunnable (int i,Table t){
		this.index = i;
		this.table = t;
	}
	@Override
	public void run() {
		// TODO Auto-generated method stub
		table.remove(index);
	}
}
